package com.wondertek.poms.core.utils;

/**
 * @author gaozhengxing gaozhenghang@wondertek.com.cn
 * @date 2021/1/3 15:48
 * @description TODO
 */

import com.wondertek.oes.sso.common.util.StringUtil;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.*;

public class HttpClientUtil {
    public static Log log = LogFactory.getLog(HttpClientUtil.class);
    private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    private static HttpClient client;
    private static int maxHostConnections = 100;
    private static int maxTotalConnections = 50;
    private static int connectionTimeOut = 15000;

    public HttpClientUtil() {
    }

    public static String requestGet(String url) {
        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
        return getResponseStr(getMethod);
    }

    public static String requestGet(String url, NameValuePair[] values) {
        GetMethod getMethod = new GetMethod(url);
        getMethod.setQueryString(values);
        getMethod.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
        return getResponseStr(getMethod);
    }

    public static String requestGet(String url, int outTime) {
        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
        return getResponseStr(getMethod);
    }

    public static int getRequestStatusCode(String url, Map<String, String> headerMap, int outTime) {
        List<String> headerList = new ArrayList();
        headerList.add("X-UP-BEAR-TYPE".toLowerCase());
        headerList.add("x-up-calling-line-id".toLowerCase());
        headerList.add("referer".toLowerCase());
        headerList.add("User-Agent".toLowerCase());
        headerList.add("WDAccept-Encoding".toLowerCase());
        int statusCode = 0;
        GetMethod getMethod = new GetMethod(url);

        try {
            StringBuffer sb = new StringBuffer();
            if (headerMap != null && headerMap.size() > 0) {
                Iterator it = headerMap.keySet().iterator();

                while (it.hasNext()) {
                    String key = (String) it.next();
                    if (headerList.contains(key.toLowerCase())) {
                        getMethod.setRequestHeader(key, (String) headerMap.get(key));
                        sb.append(key + "=" + (String) headerMap.get(key) + ", ");
                    }
                }
            }

            log.info("[URL=" + url + ", " + sb.toString() + "]");
            statusCode = client.executeMethod(getMethod);
            if (statusCode == 200 && getMethod.getResponseHeader("isError") != null && StringUtil.nullToBoolean(getMethod.getResponseHeader("isError").getValue())) {
                statusCode = 500;
            }
        } catch (Exception var12) {
            log.error(var12.getMessage());
        } finally {
            getMethod.releaseConnection();
        }

        return statusCode;
    }

    public static String httpClientPost(String url, List<NameValuePair[]> values) {
        PostMethod postMethod = new PostMethod(url);
        Iterator i$ = values.iterator();

        while (i$.hasNext()) {
            NameValuePair[] value = (NameValuePair[]) i$.next();
            postMethod.addParameters(value);
        }

        return getResponseStr(postMethod);
    }

    public static String httpClientPost(String url, NameValuePair[] values) {
        List<NameValuePair[]> list = new ArrayList();
        list.add(values);
        return httpClientPost(url, (List) list);
    }

    public String httpClientGet(String url) {
        GetMethod getMethod = new GetMethod(url);
        getMethod.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
        return getResponseStr(getMethod);
    }

    public static NameValuePair[] praseParameterMap(Map<String, String> map) {
        NameValuePair[] nvps = new NameValuePair[map.size()];
        Set<String> keys = map.keySet();
        int i = 0;

        for (Iterator i$ = keys.iterator(); i$.hasNext(); ++i) {
            String key = (String) i$.next();
            nvps[i] = new NameValuePair();
            nvps[i].setName(key);
            nvps[i].setValue((String) map.get(key));
        }

        return nvps;
    }

    public static String httpClientPost(String url, NameValuePair[] values, String xml) {
        StringBuilder sb = new StringBuilder();
        log.debug(" http url :" + url);
        NameValuePair[] arr$ = values;
        int len$ = values.length;

        for (int i$ = 0; i$ < len$; ++i$) {
            NameValuePair nvp = arr$[i$];
            log.debug(" http param :" + nvp.getName() + " = " + nvp.getValue());
        }

        PostMethod method = new PostMethod(url);
        method.setQueryString(values);
        method.addRequestHeader("Content-Type", "text/xml;charset=UTF-8");
        RequestEntity reis = null;
        InputStream input = null;
        InputStream is = null;
        BufferedReader dis = null;

        try {
            input = new ByteArrayInputStream(xml.getBytes("utf-8"));
            reis = new InputStreamRequestEntity(input);
            method.getParams().setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler());
            method.setRequestEntity(reis);
            client.executeMethod(method);
            is = method.getResponseBodyAsStream();
            dis = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String str = "";

            while ((str = dis.readLine()) != null) {
                sb.append(str);
            }
        } catch (HttpException var20) {
            var20.printStackTrace();
        } catch (IOException var21) {
            var21.printStackTrace();
        } finally {
            method.releaseConnection();

            try {
                if (dis != null) {
                    dis.close();
                }

                if (is != null) {
                    is.close();
                }

                if (input != null) {
                    input.close();
                }
            } catch (IOException var19) {
                var19.printStackTrace();
            }

        }

        return sb.toString();
    }

    public static String getResponseStr(HttpMethodBase method) {
        StringBuilder sb = new StringBuilder();

        try {
            int statusCode = client.executeMethod(method);
            if (statusCode != 200) {
                log.error("HttpClient Error : statusCode = " + statusCode + ", uri :" + method.getURI());
                String var11 = "";
                return var11;
            }

            InputStream is = method.getResponseBodyAsStream();
            BufferedReader dis = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String str = "";

            while ((str = dis.readLine()) != null) {
                sb.append(str);
            }
        } catch (Exception var9) {
            log.info("调用远程出错;发生网络异常!");
            var9.printStackTrace();
        } finally {
            method.releaseConnection();
        }

        return sb.toString();
    }

    static {
        HttpConnectionManagerParams params = new HttpConnectionManagerParams();
        params.setDefaultMaxConnectionsPerHost(maxHostConnections);
        params.setMaxTotalConnections(maxTotalConnections);
        params.setConnectionTimeout(connectionTimeOut);
        params.setSoTimeout(connectionTimeOut);
        connectionManager.setParams(params);
        client = new HttpClient(connectionManager);
        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    }
}